package com.sm.dao;

import com.sm.entity.News;
import org.apache.ibatis.annotations.*;
import org.apache.ibatis.mapping.FetchType;

import java.util.List;

public interface NewsDao {

    /**
     * @return 返回所有新闻
     */
    @Select("select * from news")
    @Results(id = "NewsMap",value = {
            @Result(id = true, property = "nid", column = "nid"),
            @Result(property = "author", column = "author", one = @One(select = "com.sm.dao.UserDao.findByUid"))
    })
    public List<News> findAllNews();

    /**
     * @return 返回所有新闻分页
     */
    @Select("select * from news order by date desc,nid desc")
    @ResultMap("NewsMap")
    public List<News> findNewsPh();

    /**
     * @param nid 要查找的新闻id
     * @return 返回一条新闻
     */
    @Select("select * from news where nid = #{nid}")
    @ResultMap("NewsMap")
    public News findNewsByNid(Integer nid);

    @Select("select * from news order by date desc,nid desc limit #{limit}")
    @ResultMap("NewsMap")
    public List<News> findNowNews(Integer limit)throws Exception;

    //添加
    /**
     * @param news 要添加的新闻
     */
    @Options(useGeneratedKeys = true, keyProperty = "nid", keyColumn = "nid")
    @Insert("insert into news(title,content,date,author,status) values(#{title},#{content},#{date},#{author.uid},#{status})")
    public void addNews(News news);

    //修改

    /**
     * @param news 要修改的新闻 只修改标题，内容
     */
    @Update("<script>" +
            "update news " +
            "<set> " +
            " <if test='title != null'>title = #{title,jdbcType=VARCHAR},</if> " +
            " <if test='content != null'>content = #{content,jdbcType=VARCHAR},</if> " +
            " </set> " +
            " where nid = #{nid,jdbcType=INTEGER}" +
            "</script>")
    public void updateNews(News news);

    /**
     * @param news 新闻要更新的状态
     */
    @Update("update news set status = #{status} where nid = #{nid}")
    public void updateStatus(News news);

    //删除

    /**
     * @param nid 要隐藏的新闻
     */
    @Update("update news set status = 0 where nid = #{nid}")
    public void deleteNews(Integer nid);

    /**
     * @param nid 要删除的新闻id
     */
    @Delete("delete from news where nid = #{nid}")
    public void clearNews(Integer nid);
}
